package com.epfresh.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.activity.ForgetPasdActivity;
import com.epfresh.activity.ListStoreActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.*;
import com.epfresh.activity.MyInfoActivity;
import com.epfresh.activity.MyOrderActivity;
import com.epfresh.activity.MyWalletActivity;
import com.epfresh.activity.OrderMinusListActivity;
import com.epfresh.activity.SelectNameEnsureActivity;
import com.epfresh.activity.SetActivity;
import com.epfresh.activity.WebActivity;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.basedialog.ShareDialog;
import com.epfresh.bean.OrderNumberHintEntity;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.User;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.BaseFragment;
import com.google.gson.Gson;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wzh on 16-7-1.
 */
public class MineFragment extends BaseFragment {


    private ImageView headImage;
    private TextView nicknameTV;
    private TextView phoneTV;
    private View myInfoView;

    private TextView tvGetPhone, tvPhone, tvQuestion, tvPassword, tvFriend, tvSetting;
    TextView tvBook,tvCoupon,tvWallet;

    private ImageView ivEnsureFlag;
    private TextView tvEnsureFlag;
    private TextView tvEnsure;

    private TextView tvWaitPay, tvWaitPost, tvWaitReceive, tvWaitEvaluate, tvMinus, tvAll;
    private MsgView msgWaitPay, msgWaitPost, msgWaitReceive, msgWaitEvaluate, msgMinus;


    Context mContext;

    @Override
    public String getBaseTag() {
        return "mineFragment";
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine,
                container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        initView(v);
        Log.i("oncreateView", "test");
        //  mHttpLoad();
        if (getUser() != null) {
            updateAvatar(getUser().getAvatar());
        }
        updateUserProfile();
    }
    View tvNew;
    void initView(View v) {
        View myOrder = v.findViewById(R.id.tv_my_order);
        myOrder.setOnClickListener(this);
        tvWaitPay = (TextView) v.findViewById(R.id.tv_wait_pay);
        tvWaitPost = (TextView) v.findViewById(R.id.tv_wait_post);
        tvWaitReceive = (TextView) v.findViewById(R.id.tv_wait_receive);
        tvWaitEvaluate = (TextView) v.findViewById(R.id.tv_wait_evaluate);
        tvMinus = (TextView) v.findViewById(R.id.tv_minus);
        tvAll = (TextView) v.findViewById(R.id.tv_all);
        tvWaitPay.setOnClickListener(this);
        tvWaitPost.setOnClickListener(this);
        tvWaitReceive.setOnClickListener(this);
        tvWaitEvaluate.setOnClickListener(this);
        tvMinus.setOnClickListener(this);
        tvAll.setOnClickListener(this);


        msgWaitPay = (MsgView) v.findViewById(R.id.msg_wait_pay);
        msgWaitPost = (MsgView) v.findViewById(R.id.msg_wait_post);
        msgWaitReceive = (MsgView) v.findViewById(R.id.msg_wait_receive);
        msgWaitEvaluate = (MsgView) v.findViewById(R.id.msg_wait_evaluate);
        msgMinus = (MsgView) v.findViewById(R.id.msg_minus);


        headImage = (ImageView) v.findViewById(R.id.image_head);
        phoneTV = (TextView) v.findViewById(R.id.phone);
        nicknameTV = (TextView) v.findViewById(R.id.nickname);
        myInfoView = v.findViewById(R.id.my_info);
        myInfoView.setOnClickListener(this);

        tvWallet = (TextView) v.findViewById(R.id.tv_wallet);
        tvCoupon = (TextView) v.findViewById(R.id.tv_coupons);
        tvCoupon.setOnClickListener(this);
        tvBook = (TextView) v.findViewById(R.id.tv_book);
/*        SharedPreferences sp = FileUtil.getSharedPreferences();
        if(sp.getInt("newFlag",0)==0){
            tvNew = v.findViewById(R.id.tv_new);
            tvNew.setVisibility(View.VISIBLE);
        }*/
        tvBook.setOnClickListener(this);
        tvWallet.setOnClickListener(this);
        tvGetPhone = (TextView) v.findViewById(R.id.tv_get_phone);
        tvPhone = (TextView) v.findViewById(R.id.tv_phone);
        tvQuestion = (TextView) v.findViewById(R.id.tv_question);
        tvPassword = (TextView) v.findViewById(R.id.tv_password);
        tvFriend = (TextView) v.findViewById(R.id.tv_friend);

        tvEnsure = (TextView) v.findViewById(R.id.tv_ensure);
        tvEnsure.setOnClickListener(this);
        tvEnsureFlag = (TextView) v.findViewById(R.id.tv_ensure_flag);
        tvEnsure.setClickable(false);
        tvEnsureFlag.setClickable(false);
        ivEnsureFlag = (ImageView) v.findViewById(R.id.iv_ensure_flag);
        tvSetting = (TextView) v.findViewById(R.id.tv_setting);

        tvEnsureFlag.setOnClickListener(this);
        tvPhone.setOnClickListener(this);
        tvGetPhone.setOnClickListener(this);
        tvQuestion.setOnClickListener(this);
        tvPassword.setOnClickListener(this);
        tvFriend.setOnClickListener(this);
        tvSetting.setOnClickListener(this);
        View tvConcern = v.findViewById(R.id.tv_concern);
        tvConcern.setOnClickListener(this);

        View actionbar = v.findViewById(R.id.action_bar);
        int statusBarHeight = 0;
        if (Constant.isStatusBar) {
            int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resId > 0) {
                statusBarHeight = getResources().getDimensionPixelSize(resId);
            } else {
                statusBarHeight = LocalDisplay.SCREEN_HEIGHT_PIXELS / 25;
            }
            actionbar.setPadding(0, statusBarHeight, 0, 0);
        }
        ViewGroup.LayoutParams lp = actionbar.getLayoutParams();
        lp.height = statusBarHeight + getResources().getDimensionPixelSize(R.dimen.height_title);
        actionbar.setLayoutParams(lp);


        mContext = this.getActivity();
        tvEnsure.setClickable(false);
        tvEnsureFlag.setClickable(false);
    }


    public void updateUserProfile() {
        if (getActivity() == null) {
            return;
        }
        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("flag", "main");
            startActivity(intent);

        } else {
            RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
            data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_profile);
            //data.setToken(getUser().getToken());

            // data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("accountId", getUser().getAccountId());

            data.setParameters(map);
            request(data, AppPurchaseRouterConstant.cmd_account_acc_profile, onRequestListener);
        }
    }

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            User user = response.getResponseElement();
            if (user == null || getActivity() == null) {
                return;
            }
            user.setAccess_token(getUser().getAccess_token());
            user.setAccountId(getUser().getAccountId());
            user.setPassword(getUser().getPassword());
            user.setTag(UUID.randomUUID().toString());
            updateUser(user);
            updateView(user);

        }
    };

    public void onResume() {
        if (getUser() != null) {
            updateView(getUser());
            mHttpOrderHint();
        }
        super.onResume();
    }


    private void updateView(User user) {
        updateAvatar(getUser().getAvatar());
        if (TextUtils.isEmpty(user.getNickname())) {
            nicknameTV.setVisibility(View.GONE);
        } else {
            nicknameTV.setVisibility(View.VISIBLE);
        }
        nicknameTV.setText(user.getNickname());
        if (user.getPhone() != null && user.getPhone().length() > 10)
            phoneTV.setText(user.getPhone().substring(0, 3) + "****" + user.getPhone().substring(7));
             /*
                    0:未认证；1：认证中；2：已认证；3：认证失败
                    * */
       /* if (user.isHasCert()) {//是否
            // name_flagIV.setVisibility(View.VISIBLE);
            ivEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setVisibility(View.VISIBLE);
        } */
        if (1 == (getUser().getCertStatus())) {/////调整实名认证状态的一致性
            tvEnsureFlag.setText("认证中");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setClickable(false);
            ivEnsureFlag.setVisibility(View.GONE);
            tvEnsure.setClickable(false);
        } else if (2 == (getUser().getCertStatus())) {

            tvEnsureFlag.setText("已认证");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            ivEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setClickable(false);
            tvEnsure.setClickable(false);
        } else if (3 == (getUser().getCertStatus())) {
            tvEnsureFlag.setText("认证失败");
            tvEnsureFlag.setVisibility(View.VISIBLE);
            tvEnsureFlag.setClickable(true);
            tvEnsure.setClickable(true);
            ivEnsureFlag.setVisibility(View.GONE);
        } else {

            tvEnsureFlag.setClickable(true);
            tvEnsure.setClickable(true);
            tvEnsureFlag.setText("未认证");
            ivEnsureFlag.setVisibility(View.GONE);
        }
        updateAvatar(user.getAvatar());
    }

    private void updateAvatar(String url) {
        String urlHead = null;
        if (url != null) {
            String[] split = url.split("-AVATAR?");
            if (split.length > 1) {
                urlHead = split[0];
            }
        }
        if (urlHead == null) {
            urlHead = url;
        }
        ImageLoader.getInstance().displayImage(urlHead, new ImageViewAware(headImage), BaseApplication.getAvatarOptions(url), null, null, null);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_my_order:
              /*  Intent order = new Intent(getActivity(), MyOrderActivity.class);
                startActivity(order);*/
                break;
            case R.id.tv_wallet:
                Intent wallet = new Intent(getActivity(), MyWalletActivity.class);
                startActivity(wallet);
                break;
            case R.id.tv_coupons:
                Intent coupons = new Intent(getActivity(), MyCouponActivity.class);
                startActivity(coupons);
                break;
            case R.id.tv_book:
                /*SharedPreferences sp = FileUtil.getSharedPreferences();
                if(sp.getInt("newFlag",0)==0){
                    tvNew = v.findViewById(R.id.tv_new);
                    tvNew.setVisibility(View.VISIBLE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putInt("newFlag", 1);
                    edit.commit();
                }*/
/*                if(tvNew!=null) {
                    SharedPreferences sp = FileUtil.getSharedPreferences();
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putInt("newFlag", 1);
                    edit.commit();
                    tvNew.setVisibility(View.INVISIBLE);
                }*/
                Intent book = new Intent(getActivity(), BookActivity.class);
                startActivity(book);
                break;
            case R.id.tv_wait_pay:
                Intent noPayList = new Intent(getActivity(), MyOrderActivity.class);
                noPayList.putExtra("type", 1);
                startActivity(noPayList);
                break;
            case R.id.tv_wait_post:
                Intent doingList = new Intent(getActivity(), MyOrderActivity.class);
                doingList.putExtra("type", 2);
                startActivity(doingList);
                break;
            case R.id.tv_wait_receive:
                Intent doneList = new Intent(getActivity(), MyOrderActivity.class);
                doneList.putExtra("type", 3);
                startActivity(doneList);
                break;
            case R.id.tv_wait_evaluate:
                Intent evaluate = new Intent(getActivity(), MyOrderActivity.class);
                evaluate.putExtra("type", 4);
                startActivity(evaluate);
                break;
            case R.id.tv_minus:
                Intent minusList = new Intent(getActivity(), OrderMinusListActivity.class);
                startActivity(minusList);
                break;
            case R.id.tv_all:
                Intent orderList = new Intent(getActivity(), MyOrderActivity.class);
                startActivity(orderList);
                break;
            case R.id.tv_get_phone:
            case R.id.tv_phone:
                Intent intent_call0 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000588198"));//调出来拨打页面；
                startActivity(intent_call0);
                break;
            case R.id.tv_question:
/*                Intent myaddress = new Intent(getActivity(), QuestionActivity.class);
                startActivity(myaddress);*/
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_EP_CLASSROOM);
                intent.putExtra(Constant.KEY_WEB_TITLE, "e批课堂");
                startActivity(intent);
                break;
            case R.id.tv_password:
                Intent password = new Intent(getActivity(), ForgetPasdActivity.class);
                startActivity(password);
                break;
            case R.id.tv_friend:
                share();
                break;
            case R.id.tv_setting:
                Intent setting = new Intent(getActivity(), SetActivity.class);
                startActivity(setting);
                break;
            case R.id.tv_ensure:
            case R.id.tv_ensure_flag:
            case R.id.iv_ensure_flag:
                if (getUser().getCertStatus() != 1 && getUser().getCertStatus() != 2) {
                    Intent ensure = new Intent(getActivity(), SelectNameEnsureActivity.class);
                    ensure.putExtra("home_tab_index",3);
                    startActivity(ensure);
                }
                break;

            case R.id.my_info:
                Intent info = new Intent(getActivity(),
                        MyInfoActivity.class);
                startActivity(info);
                break;
            case R.id.tv_concern:
                Intent attention = new Intent(getActivity(), MineAttentionActivity.class);
                attention.putExtra("name", "我的关注");
                startActivity(attention);
                break;
            default:
                break;
        }
    }

    ShareDialog dialog;

    private void share() {
        if (dialog == null)
            dialog = new ShareDialog(getActivity());
//        dialog.showDialog();

        dialog.showDialog(com.epfresh.api.constant.Constant.URL_SHARE_DOWNLOAD, "http://m.epfresh.com/images/app-purlogo.png", "国内领先的农产品交易服务平台，网上批发、产地直采，更省、更赚钱", "e批生鲜APP");
    }



    /*  "cmd": "appOrder/myOrder",
    "accountId": "94"*/

    /**
     */
    public void mHttpOrderHint() {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_order_order_my);
        Map<String, String> map = new HashMap<>();
        if(getUser()==null||getUser().getAccountId()==null){
            return;
        }
        map.put("accountId", getUser().getAccountId());
        data.setParameters(map);

        ApplicationHelper.getInstance().requestSilent(data, AppPurchaseRouterConstant.cmd_order_order_my, new OnRequestListener<OrderNumberHintEntity>() {
            @Override
            public OrderNumberHintEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, OrderNumberHintEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                //Toast.makeText(context, "服务器开小差了……", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
               // T.toast((arg == null ? "" : arg + ""));
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<OrderNumberHintEntity> response, Object tag) {
                OrderNumberHintEntity responseElement = response.getResponseElement();
                show(msgWaitPay, responseElement.getBepay());
                show(msgWaitPost, responseElement.getStock());
                show(msgWaitReceive, responseElement.getBetake());
                show(msgWaitEvaluate, responseElement.getBepj());
                show(msgMinus, responseElement.getJmt());
            }
        });
    }

    void show(MsgView msgView, int num) {
        if (num == 0) {
            msgView.setVisibility(View.GONE);
        } else {
            UnreadMsgUtils.show(msgView, num);
        }
    }

}
